<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

const BRAND = '比亚迪';
//echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => BRAND]);


//获取车辆类型
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://www.bydauto.com.cn/auto/BrandWorld/SearchDealers.html', [
    'wd' => 'QueryList'
]);
$html = (string)$res->getBody();

/*
$rules=[
    'model'=>['#car-modal option','text'],
];
$data = QueryList::get("http://www.bydauto.com.cn/auto/BrandWorld/SearchDealers.html")->rules($rules)->query()->getData();
*/
$data = QueryList::html($html)->find('#car-modal option')->texts();
$car = $data->all();
unset($car[0]);

//获取省份--城市
$tpc = [];//type-provinces-city

$dealer = [];

foreach ($car as $v) {

    $type = urlencode($v);
    $url = "http://www.bydauto.com.cn/sites/custom/service/auto/sales?type=getBeforeSaleProvinces&carType=$type";

    $rt = QueryList::get($url)->find('option')->texts();

    $p = $rt->all();

    //循环省份获取城市
    foreach ($p as $a) {
        $p = urlencode($a);
        $url2 = "http://www.bydauto.com.cn/sites/custom/service/auto/sales?type=getBeforeSaleCitys&carType=$type&province=$p";
        $rc = QueryList::get($url2)->find('option')->texts();
        $city = $rc->all();


        foreach ($city as $b) {

            //$tpc[]=['type'=>$v,'pr'=$a,'city'=$c];
            $c = urlencode($b);
            $url3 = "http://www.bydauto.com.cn/sites/custom/service/auto/sales?type=getBeforeSaleStores&carType=$type&province=$p&city=$c";
            $ql = QueryList::post($url3);
            $content = (string)$ql->getHtml();

            $service = json_decode($content, true);


            foreach ($service as $item) {

                if (in_array($item['sjname'], $dealer)) {
                    continue;

                }


                $dealer[] = $item['sjname'];

                $db->insert('tDealer', [
                    'sDealerName' => $item['sjname'],
                    'nBrandID' => '',
                    'sBrand' => BRAND,
                    'sProvince' => $a,
                    'sCity' => $b,
                    'sAddress' => $item['address'],
                    'sSaleCall' => $item['phone'] ?? '',
                    'sLatitude' => $item['weidu']??'',
                    'sLongitude' => $item['jingdu'],
                    'dUpdateTime' => Medoo::raw('now()'),
                    'sManufacturer' => BRAND,
                ]);
                echo "{$item['sjname']}完成" . PHP_EOL;
            }

        }


        //获取经销商
    }


}
echo '爬虫结束' . PHP_EOL;